package com.chu.cloud.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/3/27 14:38
 * @Description: 通过Spring上下文获取bean对象
 */
@Component
public class SpringContextHolder implements ApplicationContextAware{

    private static ApplicationContext applicationContext = null;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        SpringContextHolder.applicationContext = applicationContext;

    }

    /**
     * 获取applicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name){
        return getApplicationContext().getBean(name);

    }

    /**
     * 通过class获取bean
     * @param clazz
     * @param <T>
     * @return
     */
    public static<T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过class,以及name获取指定bean
     * @param clazz
     * @param name
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz,String name){
        return getApplicationContext().getBean(clazz,name);
    }
}
